/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package proyectotpa;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import tpa.TablaPeriodica.Clasificacion;
import tpa.TablaPeriodica.Elemento;
import tpa.TablaPeriodica.SubClase;
import tpa.TablaPeriodica.TablaPeriodicaSessionRemote;

/**
 *
 * @author leandro
 */
public class Main
{

    private TablaPeriodicaSessionRemote tablaPeriodicaSessionBean;
    private Context _initialContext;

    private void addElementos(SubClase subClase, String elementosIdList)
    {
        if (!elementosIdList.isEmpty())
        {
            System.out.println(elementosIdList);
            String[] ids = elementosIdList.split(",");

            System.out.println("ids length :" + ids.length);

            for (String currentId : ids)
            {
                System.out.println(currentId);
                Long id = Long.parseLong(currentId);

                Elemento elemento = this.tablaPeriodicaSessionBean.ObtenerElemento(id);
                System.out.println("Adding " + elemento.toString());
            //subClase.add(elemento);
            }
        }
        System.out.println("done.");
    }

    private Context getInitialContext() throws NamingException
    {
        if (_initialContext == null)
        {
            _initialContext = new InitialContext(System.getProperties());
        }

        return _initialContext;
    }

    private TablaPeriodicaSessionRemote getTablaPeriodicaSessionBean() throws NamingException
    {
        if (tablaPeriodicaSessionBean == null)
        {
            tablaPeriodicaSessionBean = (TablaPeriodicaSessionRemote) getInitialContext().lookup("TablaPeriodicaSessionBean#tpa.TablaPeriodica.TablaPeriodicaSessionRemote");
        //tablaPeriodicaSessionBean = (TablaPeriodicaSessionRemote) getInitialContext().lookup("TablaPeriodicaSessionBean");
        }

        return tablaPeriodicaSessionBean;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        try
        {
            Main mainApp = new Main();

            mainApp.run(args);
        }
        catch (Exception exception)
        {
            System.err.println(exception.getMessage());
        }
    }

    public void run(String[] args) throws Exception
    {
        System.out.println("Jndi session bean: " + getTablaPeriodicaSessionBean());

        mainMenu();
    }

    @SuppressWarnings("empty-statement")
    public int getUserChoice(String menu) throws IOException
    {
        String[] options = menu.split("\n");

        do
        {
            System.out.println();
            for (String currentOption : options)
            {
                System.out.println(currentOption);
            }
            char choice;

            while ((choice = (char) System.in.read()) == '\n');

            for (int currentOptionIndex = 0; currentOptionIndex < options.length; currentOptionIndex++)
            {
                String currentOption = options[currentOptionIndex].trim();

                int startIndex, endIndex;

                if (currentOption.charAt(0) == choice)
                {
                    return currentOptionIndex;
                }
                else
                {
                    if ((startIndex = currentOption.indexOf("(")) > 0)
                    {
                        if ((endIndex = currentOption.indexOf(")")) > currentOption.indexOf("("))
                        {
                            char optionShortCut = currentOption.substring(startIndex + 1, endIndex).charAt(0);
                            if (Character.toLowerCase(optionShortCut) == Character.toLowerCase(choice))
                            {
                                return currentOptionIndex;
                            }
                        }
                    }
                }
            }
        } while (true);
    }

    public void mainMenu() throws IOException
    {
        int selection;

        while ((selection = getUserChoice("1 - (C)lasificaciones\n2 - (E)lementos\n3 - (S)alir")) != 2)
        {
            switch (selection)
            {
                case 0:
                    this.clasificacionesMainMenu();
                    break;
                case 1:
                    this.elementosMainMenu();
                    break;
            }
        }
    }

    private void clasificacionesMainMenu() throws IOException
    {
        int selection;

        while ((selection = getUserChoice("1 - (L)istar Clasificacion\n2 - (A)gregar Clasificacion\n3 - (Q)uitar Clasificacion\n4 - L(i)star SubClases\n5 - A(g)regar SubClases\n6 - Q(u)itar Subclase\n7 - (S)alir")) != 6)
        {
            switch (selection)
            {
                case 0:
                    this.listarClasificaciones();
                    break;
                case 1:
                    this.agregarClasificacion();
                    break;
                case 2:
                    this.eliminarClasificacion();
                    break;
                case 3:
                    this.listarSubClases();
                    break;
                case 4:
                    this.agregarSubClase();
                    break;
                case 5:
                    this.eliminarSubClase();
                    break;

            }
        }
    }

    private void listarSubClases() throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        br.readLine();

        System.out.print("Ingrese Nombre Clasificacion padre: ");
        String nombreClasificacion = br.readLine();

        List subClases = this.tablaPeriodicaSessionBean.ObtenerSubClases(nombreClasificacion);

        if (subClases.isEmpty())
        {
            System.out.println("No hay elementos.");
        }
        else
        {
            System.out.println("Lista de elementos (" + subClases.size() + ")");
            for (int currentIndex = 0; currentIndex < subClases.size(); currentIndex++)
            {
                System.out.println(subClases.get(currentIndex));
            }
        }
    }

    private void agregarSubClase() throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        br.readLine();

        SubClase subClase = new SubClase();

        System.out.print("Ingrese Nombre Clasificacion padre: ");
        String nombreClasificacion = br.readLine();
        Clasificacion clasificacion = this.tablaPeriodicaSessionBean.ObtenerClasificacion(nombreClasificacion);

        System.out.print("Ingrese valor de la subClase: ");
        subClase.setValor(br.readLine());

        System.out.print("Ingrese lista de elementos (1, 2, 3, ...)");
        this.addElementos(subClase, br.readLine());

        System.out.println("Agregando subclase a clasificacion");
        clasificacion.add(subClase);

        this.tablaPeriodicaSessionBean.AgregarSubClase(subClase);

        System.out.println("SubClase " + subClase.toString() + " Agregada");

    }

    private void eliminarSubClase()
    {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private void agregarClasificacion()
    {
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            Clasificacion clasificacion = new Clasificacion();

            br.readLine();

            System.out.print("Ingrese Nombre: ");
            clasificacion.setNombre(br.readLine());

            this.tablaPeriodicaSessionBean.AgregarClasificacion(clasificacion);

            System.out.println("Clasificacion " + clasificacion.toString() + " agregada.");
        }
        catch (Exception exception)
        {
            System.err.println(exception.getMessage());
        }
    }

    private void eliminarClasificacion()
    {
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            System.out.println("Ingrese Id:");
            br.readLine();

            Long clasificacionId = Long.parseLong(br.readLine());

            this.tablaPeriodicaSessionBean.EliminarClasificacion(clasificacionId);

            System.out.println("Clasificacion " + clasificacionId + " removida.");
        }
        catch (Exception exception)
        {
            System.err.println(exception.getMessage());
        }
    }

    private void listarClasificaciones()
    {
        List clasificaciones = this.tablaPeriodicaSessionBean.ObtenerClasificaciones();

        if (clasificaciones.isEmpty())
        {
            System.out.println("No hay elementos.");
        }
        else
        {
            System.out.println("Lista de elementos (" + clasificaciones.size() + ")");
            for (int currentIndex = 0; currentIndex < clasificaciones.size(); currentIndex++)
            {
                System.out.println(clasificaciones.get(currentIndex));
            }
        }
    }

    public void elementosMainMenu() throws IOException
    {
        int selection;

        while ((selection = getUserChoice("1 - (L)istar Elementos\n2 - (A)gregar Elemento\n3 - (Q)uitar Elemento\n4 - (S)alir")) != 3)
        {
            switch (selection)
            {
                case 0:
                    this.listarElementos();
                    break;
                case 1:
                    this.agregarElemento();
                    break;
                case 2:
                    this.quitarElemento();
                    break;
            }
        }
    }

    private void agregarElemento() throws IOException
    {
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            Elemento elemento = new Elemento();

            br.readLine();

            System.out.print("Ingrese Número Atómico: ");
            elemento.setId(Long.parseLong(br.readLine()));

            System.out.print("Ingrese Nombre: ");
            elemento.setNombre(br.readLine());

            System.out.print("Ingrese Símbolo: ");
            elemento.setSimbolo(br.readLine());

            System.out.print("Ingrese Peso Atómico: ");
            elemento.setPesoAtomico(Float.parseFloat(br.readLine()));

            this.tablaPeriodicaSessionBean.AgregarElemento(elemento);

            System.out.println("Elemento " + elemento.toString() + " agregado.");
        }
        catch (Exception exception)
        {
            System.err.println(exception.getMessage());
        }
    }

    private void listarElementos()
    {
        List elementos = this.tablaPeriodicaSessionBean.ObtenerElementos();

        if (elementos.isEmpty())
        {
            System.out.println("No hay elementos.");
        }
        else
        {
            System.out.println("Lista de elementos (" + elementos.size() + ")");
            for (int currentIndex = 0; currentIndex < elementos.size(); currentIndex++)
            {
                System.out.println(elementos.get(currentIndex));
            }
        }
    }

    private void quitarElemento() throws IOException
    {
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            System.out.println("Ingrese Id:");
            br.readLine();

            Long numeroAtomico = Long.parseLong(br.readLine());

            this.tablaPeriodicaSessionBean.EliminarElemento(numeroAtomico);

            System.out.println("Elemento " + numeroAtomico + " removido.");
        }
        catch (Exception exception)
        {
            System.err.println(exception.getMessage());
        }
    }
}
